<template>
  <div v-if="!item.hidden">
    <template
      v-if="
        hasOneShowingChild(item.children, item) &&
        (!onlyOneChild.children || onlyOneChild.noShowingChildren) &&
        !item.alwaysShow
      "
    >
      <app-link
        v-if="onlyOneChild.meta"
        :value="resolvePath(onlyOneChild.path)"
        :to="resolvePath(onlyOneChild.path, onlyOneChild.query)"
      >
        <template #icon>
          <svg-icon :name="onlyOneChild.meta.icon || (item.meta && item.meta.icon)"></svg-icon>
        </template>
        <div class="m-l-4">{{ onlyOneChild.meta.title }}</div>
      </app-link>
    </template>

    <t-submenu v-else :value="resolvePath(item.path)">
      <template #icon>
        <svg-icon :name="item.meta && item.meta.icon"></svg-icon>
      </template>
      <template #title>
        <div class="m-l-4">{{ item.meta && item.meta.title }}</div>
      </template>
      <side-bar-item
        v-for="child in item.children"
        :key="child.path"
        :is-nest="true"
        :item="child"
        :base-path="resolvePath(child.path)"
      />
    </t-submenu>
  </div>
</template>
<script setup lang="ts">
import { isExternal } from '@/utils/is.ts';
import AppLink from '@/layouts/components/RxMenuSidebar/Link.vue';
import SideBarItem from '@/layouts/components/RxMenuSidebar/index.vue';
import { resolve } from 'path-browserify';

interface IProps {
  item?: any;
  isNest?: boolean;
  basePath?: string;
}
const props = withDefaults(defineProps<IProps>(), {
  isNest: false,
  basePath: '',
});
let onlyOneChild: any = null;

const hasOneShowingChild = (children: any[] = [], parent: any) => {
  if (!children) {
    children = [];
  }
  const showingChildren = children.filter((item) => {
    if (item.hidden) {
      return false;
    } else {
      // Temp set(will be used if only has one showing child)
      onlyOneChild = item;
      return true;
    }
  });

  // When there is only one child router, the child router is displayed by default
  if (showingChildren.length === 1) {
    return true;
  }

  // Show parent if there are no child router to display
  if (showingChildren.length === 0) {
    onlyOneChild = { ...parent, path: '', noShowingChildren: true };
    return true;
  }

  return false;
};

const resolvePath = (routePath: string, routeQuery?: string) => {
  if (isExternal(routePath)) {
    return routePath;
  }
  if (isExternal(props.basePath)) {
    return props.basePath;
  }
  if (routeQuery) {
    let query = JSON.parse(routeQuery);
    return { path: resolve(props.basePath, routePath), query: query };
  }
  return resolve(props.basePath, routePath);
};
</script>
